package com.example.wc.logindemo;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;

import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.ImageLoader;
import com.example.wc.logindemo.getdownload.GetDownloadActivity;
import com.example.wc.logindemo.getdownload.GetDownloadFragment;
import com.example.wc.logindemo.getdownload.ImageLoaderActivity;
import com.example.wc.logindemo.postupload.SystemPicturePath;
import com.example.wc.logindemo.postupload.UploadApi;

import org.json.JSONObject;

import java.io.File;

/**
 * Created by hui on 2017/3/21.
 */

public class PictureBlogActivity extends AppCompatActivity {
    private static final int REQUEST_PHOTO = 0;
    private static final int REQUEST_PHOTO_CROP = 1;
    private static final int REQUEST_PICK_PICTURE = 2;

    private Button mTakePhotoButton;
    private Button mPickPictureButton;

    private Button mCancelButton;

    private ImageView mPictureImageView;
    private File mPhotoFile;
    private File mPhotoCropFile;
    private File mPhotoSystemFile;
    private Blog mBlog;
    private Uri uri;
    private Uri cropUri;
    private Uri systemUri;
    private Bitmap bitmap;//回收bitmap防止内存泄漏

    private ProgressDialog mDialog;

    //activity销毁时回收图片内存防止内存泄漏,如果不置空会出错，bitmap被回收，再进入imageView不显示图片报错
    @Override
    public void onDestroy(){
        super.onDestroy();
        if(bitmap != null && !bitmap.isRecycled()){
            bitmap.recycle();
            bitmap = null;
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.picture_select_camera_crop);

        PackageManager packageManager = PictureBlogActivity.this.getPackageManager();
        String blogId = "58c9103974045363e5510952";
        mBlog = BlogLab.get(PictureBlogActivity.this).getBlog(blogId);
        mPhotoFile = BlogLab.get(PictureBlogActivity.this).getPhotoFile(mBlog);
        mPhotoCropFile = BlogLab.get(PictureBlogActivity.this).getPhotoCropFile(mBlog);

        mTakePhotoButton = (Button)findViewById(R.id.picture_selector_take_photo_btn);
        final Intent captureImage = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

        boolean canTakePhoto = mPhotoFile != null &&
                captureImage.resolveActivity(packageManager) != null;
        mTakePhotoButton.setEnabled(canTakePhoto);

        if(canTakePhoto){
            uri = Uri.fromFile(mPhotoFile);
            captureImage.putExtra(MediaStore.EXTRA_OUTPUT, uri);
        }

        mTakePhotoButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivityForResult(captureImage, REQUEST_PHOTO);
            }
        });

        mPictureImageView = (ImageView)findViewById(R.id.picture_image_view);
        mPickPictureButton = (Button)findViewById(R.id.picture_selector_pick_picture_btn);
        mPickPictureButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(Intent.ACTION_GET_CONTENT, null);
                intent.setType("image/*");
                startActivityForResult(intent, REQUEST_PICK_PICTURE);
            }
        });

        mDialog = new ProgressDialog(this) ;
        mDialog.setCanceledOnTouchOutside(false);

        mCancelButton = (Button)findViewById(R.id.picture_selector_cancel_btn);
        mCancelButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(PictureBlogActivity.this, GetDownloadActivity.class);
                startActivity(intent);
            }
        });

        updatePhotoCropView();

    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if(resultCode != Activity.RESULT_OK){
            return;
        }

        if (requestCode == REQUEST_PHOTO){
            cropImg(uri);
//            updatePhotoView();
        }else if(requestCode == REQUEST_PHOTO_CROP){
            updatePhotoCropView();
            uploadImg();
        }else if (requestCode == REQUEST_PICK_PICTURE){
            try {
                String picPath = SystemPicturePath.parsePicturePath(PictureBlogActivity.this, data.getData());
                mPhotoSystemFile = new File(picPath);
                systemUri = Uri.fromFile(mPhotoSystemFile);
                Bitmap photo = MediaStore.Images.Media.getBitmap(getContentResolver(), systemUri);
                if (photo != null) {
                    bitmap = PictureUtils.getScaledBitmap(picPath, PictureBlogActivity.this);
                    cropImg(systemUri);
//                    mPictureImageView.setImageBitmap(bitmap);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }

        }

        super.onActivityResult(requestCode, resultCode, data);
    }

    private void updatePhotoCropView(){
        if(mPhotoCropFile == null || !mPhotoCropFile.exists()){
            mPictureImageView.setImageDrawable(null);
        }else {
            bitmap = PictureUtils.getScaledBitmap(mPhotoCropFile.getPath(), PictureBlogActivity.this);
            mPictureImageView.setImageBitmap(bitmap);
        }
    }


    public void cropImg(Uri uri) {
//        PackageManager packageManager = getActivity().getPackageManager();

        final Intent captureImageCrop = new Intent("com.android.camera.action.CROP");

//        boolean canTakePhotoCrop = //mPhotoCropFile != null &&
//                captureImageCrop.resolveActivity(packageManager) != null;
//        mPhotoButton.setEnabled(canTakePhoto);

//        if(canTakePhotoCrop){
        cropUri = Uri.fromFile(mPhotoCropFile);
        captureImageCrop.putExtra(MediaStore.EXTRA_OUTPUT, cropUri);
        captureImageCrop.setDataAndType(uri, "image/*");
        captureImageCrop.putExtra("crop", "true");
        captureImageCrop.putExtra("aspectX", 1);
        captureImageCrop.putExtra("aspectY", 1);
        captureImageCrop.putExtra("outputX", 300);
        captureImageCrop.putExtra("outputY", 300);
        captureImageCrop.putExtra("return-data", false);
        captureImageCrop.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
        captureImageCrop.putExtra("noFaceDetection", true);
//        }

        startActivityForResult(captureImageCrop, REQUEST_PHOTO_CROP);

    }

    public void uploadImg(){
        mDialog.setMessage("图片上传中...");
        mDialog.show();
//        final Bitmap bitmap = BitmapFactory.decodeResource(getResources(),R.drawable.ic_blogs_add) ;
//        Bitmap bitmap = PictureUtils.getScaledBitmap(mPhotoCropFile.getPath(), PictureBlogActivity.this);
        UploadApi.uploadImg(this,
                bitmap,
                mPhotoCropFile.getName(),
                new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {
                        mDialog.dismiss();
                        Toast.makeText(PictureBlogActivity.this,"上传成功",Toast.LENGTH_SHORT).show();
                    }
                }, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        Log.v("zgy","===========VolleyError========="+error) ;
                        Toast.makeText(PictureBlogActivity.this,"上传失败",Toast.LENGTH_SHORT).show() ;
                        mDialog.dismiss();
                    }
                }) ;
    }
}
